
package com.danjoas.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import com.danjoas.dao.AutorDao;
import com.danjoas.model.Autor;

/**
 *
 * @author Dan Joas
 */
@Repository("autorDao")
public class AutorDaoImpl implements AutorDao {

    @PersistenceContext
    private EntityManager em;

    public List<Autor> list() {
        Query q = em.createQuery("select a from Autor a");
        return q.getResultList();
    }

    public Autor getById(Integer id) {
        TypedQuery<Autor> emquery = em.createQuery("select a from Autor a WHERE a.idAutor = :id", Autor.class);
        emquery.setParameter("id", id);

        try {
            Autor autor = emquery.getSingleResult();
            return autor;

        } catch (NonUniqueResultException nure) {
            return new Autor();
        }
    }
    
    public Autor getByNombre(String nombre) {
        TypedQuery<Autor> emquery = em.createQuery("select a from Autor a WHERE a.nombres = :nombre", Autor.class);
        emquery.setParameter("nombre", nombre);

        try {
            Autor autor = emquery.getSingleResult();
            return autor;

        } catch (NonUniqueResultException nure) {
            return new Autor();
        }
    }

    public void insert(Autor autor) {

        em.persist(autor);

    }

    public void update(Autor uptedautor) {

        TypedQuery<Autor> emquery = em.createQuery("select a from Autor a WHERE a.idAutor = :id", Autor.class);
        emquery.setParameter("id", uptedautor.getIdAutor());
        Autor autor = emquery.getSingleResult();
        autor.setNombres(uptedautor.getNombres());
        autor.setApePaterno(uptedautor.getApePaterno());
        autor.setApeMaterno(uptedautor.getApeMaterno());
        em.merge(autor);
    }

    public void delete(Autor autor) {
        Query emquery = em.createQuery("DELETE from Autor a WHERE  a.idAutor = :id");
        emquery.setParameter("id", autor.getIdAutor());
        emquery.executeUpdate();
    }
}
